/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.ferryc.modules.sys.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;

import com.ferryc.commons.scan.SpringContextHolder;
import com.ferryc.commons.utils.CacheUtils;
import com.ferryc.constant.GlobalConstant;
import com.ferryc.constant.ValidatorConstant;
import com.ferryc.modules.sys.entity.SysDict;
import com.ferryc.modules.sys.mapper.ISysDictMapper;

/**
 * 字典工具类
 * 
 * @author ThinkGem
 * @version 2013-5-29
 */
public class DictUtils {

	private static ISysDictMapper dictMapper = SpringContextHolder.getBean(ISysDictMapper.class);

	public static final String CACHE_DICT_MAP = "dictMap";

	private DictUtils() {
	}

	public static String getDictLabel(String value, String type, String defaultValue) {
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)) {
			for (SysDict dict : getDictList(type)) {
				if (value.equals(dict.getTypeValue())) {
					return dict.getTypeName();
				}
			}
		}
		return defaultValue;
	}

	public static List<SysDict> getDictList(String type) {
		@SuppressWarnings("unchecked")
		Map<String, List<SysDict>> dictMap = (Map<String, List<SysDict>>) CacheUtils.get(CACHE_DICT_MAP);
		if (dictMap == null) {
			dictMap = new HashMap<>();
			SysDict sysDict = new SysDict();
			sysDict.setParentId(SysDict.SYSTEM_ID);
			for (SysDict dict : dictMapper.listByEntity(new SysDict())) {
				SysDict childDict = new SysDict();
				childDict.setParentId(dict.getId());
				childDict.setStatus(GlobalConstant.YES);
				List<SysDict> dictList = dictMapper.listByEntity(childDict);
				if (!CollectionUtils.isEmpty(dictList)) {
					dictMap.put(dict.getTypeCode(), dictList);
				}
			}
			CacheUtils.put(CACHE_DICT_MAP, dictMap);
		}
		List<SysDict> dictList = dictMap.get(type);
		if (dictList == null) {
			dictList = new ArrayList<>();
		}
		return dictList;
	}

	public static String getErrorMessage(String type) {
		return ValidatorConstant.getMessage(type);
	}
}
